package chinac

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"time"
)

var Api ChinacOpenApi

func RebootCloudPhone(phones []CloudPhone) Response {
	Api.SetHttpMethod("POST")
	Api.SetAction("RebootCloudPhone")
	params := map[string]interface{}{
		"Operate":     "reboot",
		"Remark":      "重启云手机" + time.Now().Format("2006-01-01 15:04:05"),
		"CloudPhones": phones,
	}
	Api.SetRequestParams(params)
	res, _ := Api.Do()
	return res
}

func ListCloudPhone() Response {
	Api.SetHttpMethod("POST")
	Api.SetAction("ListCloudPhone")
	params := map[string]interface{}{}
	Api.SetRequestParams(params)
	res, _ := Api.Do()
	return res
}

func DescribeCloudPhone(region string, id string) Response {
	Api.SetHttpMethod("POST")
	Api.SetAction("DescribeCloudPhone")
	params := map[string]interface{}{
		"Region": region,
		"Id":     id,
	}
	Api.SetRequestParams(params)
	res, _ := Api.Do()
	return res
}

func StartApp(region string, id string, package_ string) CmdResponse {
	signature := GetCmdApiSignature(region, id)
	data := map[string]string{"Id": id, "RToken": signature["RToken"].(string), "PackageName": package_}
	payload, _ := json.Marshal(data)
	res, _ := http.Post(signature["ApiUrl"].(string)+"/cloudPhone/cmd/startApp?Signature="+signature["Signature"].(string), "application/json", bytes.NewBuffer(payload))

	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
		}
	}(res.Body)
	body, _ := io.ReadAll(res.Body)
	var response CmdResponse
	err := Json.Unmarshal(body, &response)
	if err != nil {
		return CmdResponse{}
	}
	return response
}

func GetCmdApiSignature(region string, id ...string) map[string]interface{} {
	Api.SetHttpMethod("POST")
	Api.SetAction("GetCmdApiSignature")
	params := map[string]interface{}{
		"Region": region,
		"Ids":    id,
	}
	Api.SetRequestParams(params)
	res, _ := Api.Do()
	return res.Data
}
